﻿using DataTier;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace KlageSystem
{
    public partial class upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            System.Drawing.Image original_image = null;

            try
            {
                // Get the data
                HttpPostedFile jpeg_image_upload = Request.Files["Filedata"];
                var OrgKlagenr = Request.Form["OrgKlagenr"];
                var Klagenr = -1;
                int.TryParse(Request.Form["KlageNr"], out Klagenr);
                    

                // Retrieve the uploaded image
                original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);

                var uploadPath = Server.MapPath("~/uploads/") + OrgKlagenr;
                if (!Directory.Exists(uploadPath))
                    Directory.CreateDirectory(uploadPath);

                var filePath = uploadPath + "/" + jpeg_image_upload.FileName;
                if (File.Exists(filePath))
                {
                    Response.StatusCode = 500;
                    Response.Write("Filen findes allerede");
                    Response.End();
                }
                else
                {
                    var billede = Klage_billede.Insert(ConnectionManager.GetConnStr(), Klagenr, "uploads/" + OrgKlagenr + "/" + jpeg_image_upload.FileName);
                    original_image.Save(filePath);
                    Response.StatusCode = 200;
                }
            }
            catch
            {
                // If any kind of error occurs return a 500 Internal Server error
                Response.StatusCode = 500;
                Response.Write("An error occured");
                Response.End();
            }
            finally
            {
                // Clean up
                if (original_image != null) original_image.Dispose();
                Response.End();
            }

        }
    }
}